package com.cndw.kungfu.model.general;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsIntKey;
import com.cndw.kungfu.config.ConstantsLevel;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.config.ConstantsRadio;
import com.cndw.kungfu.core.cache.CacheCollect;
import com.cndw.kungfu.domain.Collect;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.Title;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.disciple.PlayerMartial;
import com.cndw.kungfu.model.disciple.domain.Disciple;
import com.cndw.kungfu.model.goods.domain.ModeGoodsStarSuit;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.vo.EventNotice;
import com.cndw.kungfu.vo.rankingvo.PlayerRankingVO;

/**
 * 通过模块服务方法
 * 
 * 
 * @author <a href="mailto:whz-work@163.com">汪洪州</a>
 * 
 * @since 1.0 Create on 2011-8-2
 */
@Service
public class GeneralServer {

	@Resource
	private GeneralManager generalManager;

	@Resource
	private RankingListManager rankingListManager;

	@Resource
	private CacheCollect cacheCollect;

	public int getOnlineExp(Player player) {
		return generalManager.getOnlineExp(player);
	}

	public int getOfflineExp(Player player) {
		return generalManager.getOfflineExp(player);
	}
	
	public int getWorldLevel(){
		return rankingListManager.getWorldLevel();
	}
	public Collect getCollect(int id) {
		return cacheCollect.getOne(id);
	}

	public Collection<Collect> getCollects() {
		return cacheCollect.getCollects();
	}

	public List<Collect> getCollectByType(Integer type) {
		return cacheCollect.getByType(type);
	}

	public PlayerRankingVO getPlayerRanking(Player player) {
		return rankingListManager.getPlayerRanking(player.getPlayerId());
	}

	/**
	 * 检查不可重复兑换的图鉴，玩家是否已经兑换过
	 * 
	 * @param playerId
	 * @param collectId
	 * @return
	 */
	public boolean checkCollectFinish(long playerId, int collectId) {
		return generalManager.checkCollectFinish(playerId, collectId);
	}

	private int getCount(Map<Integer, Integer> goodsCounts, int key) {
		if (goodsCounts.containsKey(key)) {
			return goodsCounts.get(key);
		}
		return 0;
	}

	/**
	 * 检查指定图鉴玩家是否的进度
	 * 
	 * @param playerBoxs
	 * @param collect
	 * @return
	 */
	public int checkProgress(Map<Integer, Integer> goodsCounts, Collect collect) {

		float sum = collect.getCounts1(), counts = 0;
		int counts1 = getCount(goodsCounts, collect.getGoodsId1());
		if (counts1 >= collect.getCounts1()) {
			counts += collect.getCounts1();
		} else {
			counts += counts1;
		}

		if (collect.getGoodsId2() > 0) { // goods 2
			sum += collect.getCounts2();
			int counts2 = getCount(goodsCounts, collect.getGoodsId2());
			if (counts2 >= collect.getCounts2()) {
				counts += collect.getCounts2();
			} else {
				counts += counts2;
			}
		}

		if (collect.getGoodsId3() > 0) { // goods 3
			sum += collect.getCounts3();
			int counts3 = getCount(goodsCounts, collect.getGoodsId3());
			if (counts3 >= collect.getCounts3()) {
				counts += collect.getCounts3();
			} else {
				counts += counts3;
			}
		}

		if (collect.getGoodsId4() > 0) { // goods 4
			sum += collect.getCounts4();
			int counts4 = getCount(goodsCounts, collect.getGoodsId4());
			if (counts4 >= collect.getCounts4()) {
				counts += collect.getCounts4();
			} else {
				counts += counts4;
			}
		}

		if (collect.getGoodsId5() > 0) { // goods 5
			sum += collect.getCounts5();
			int counts5 = getCount(goodsCounts, collect.getGoodsId5());
			if (counts5 >= collect.getCounts5()) {
				counts += collect.getCounts5();
			} else {
				counts += counts5;
			}
		}

		return Math.round(counts / sum * 100);
	}

	/**
	 * 移除称号
	 */
	public void removeTitle(long playerId, int titleId) {
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (player.getDataInfo().getTitles().contains(titleId)) {
			Title title = Context.getCacheCenter().getTitle(titleId);
			player.getDataInfo().getTitles().remove(titleId);
			player.getDataInfo().commitSync();
			if (player.getTitleId() == titleId) {
				player.setTitleId(0);
				player.commitSync();
				Context.getPlayerServer().clacProperties(player);
				if (Context.getPlayerServer().isOnline(playerId)) {
					EventNotice eNotice = new EventNotice(ConstantsRadio.title, ConstantsRadio.titleUse);
					eNotice.put("playerId", playerId);
					eNotice.put("on", false);
					eNotice.put("tdo", false);// 自己不处理
					eNotice.broadcastScene(player.getSceneId(), player.getSubLine());// 广播单线
					eNotice.put("player", player.toPlayerVO());
					eNotice.put("tdo", true);// 自己要处理
					eNotice.broadcast(playerId);// 广播自己
				}
			}

			Context.getMessageServer().recordEvent(playerId, LanguageLib.get("player.title.removetitle"), LanguageLib.get("player.title.remove", title.getTitleName()),
					Constants.eventTypeNormal);

		}
	}

	/**
	 * 添加称号
	 */
	public void addTitle(long playerId, int titleId) {
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (!player.getDataInfo().getTitles().contains(titleId)) {
			Title title = Context.getCacheCenter().getTitle(titleId);
			player.getDataInfo().getTitles().add(titleId);
			player.getDataInfo().commitSync();

			if (Context.getPlayerServer().isOnline(playerId)) {
				EventNotice eNotice = new EventNotice(ConstantsRadio.title, ConstantsRadio.titleUse);
				eNotice.put("on", true);
				eNotice.put("playerId", playerId);
				eNotice.put("titleId", titleId);
				eNotice.put("tdo", true);// 自己要处理
				
				eNotice.put("newName", title.getTitleName());
				eNotice.put("newQuality", title.getQuality());
				eNotice.put("newAttri", title.getAddAttri());
				if (player.getTitleId() > 0) {
					Title oldTitle = Context.getCacheCenter().getTitle(player.getTitleId());
					eNotice.put("oldId", oldTitle.getId());
					eNotice.put("oldName", oldTitle.getTitleName());
					eNotice.put("oldQuality", oldTitle.getQuality());
					eNotice.put("oldAttri", oldTitle.getAddAttri());
				}
				
				eNotice.broadcast(playerId);
			}
			Context.getMessageServer().recordEvent(playerId, LanguageLib.get("player.title.addtitle"), LanguageLib.get("player.title.add", title.getTitleName()),
					Constants.eventTypeNormal);

		}
	}

	/**
	 * 是否已经获得了称号
	 */
	public boolean hasTitle(long playerId, int titleId) {
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		return player.getDataInfo().getTitles().contains(titleId);
	}

	/**
	 * 添加称号
	 * 
	 * @param playerId
	 * @param titleType
	 * @param delay
	 *            延迟时间
	 */
	public void addTilte(final long playerId, int titleType, int delay) {
		final List<Title> titles = Context.getCacheCenter().getTitles(titleType);
		final Player player = Context.getPlayerServer().getByPlayerId(playerId);
		switch (titleType) {
		case Constants.titleUpStar:
			int suitStar = 0;
			List<ModeGoodsStarSuit> suit = ModeGoodsStarSuit.getStarSuite(player.getPlayerBoxs().getEquipList());
			for (ModeGoodsStarSuit e : suit) {
				if (e.isActived() && suitStar < e.getLevel()) {
					suitStar = e.getLevel();
				}
			}
			if (suitStar != 0) {
				for (Title title : titles) {
					if (suitStar >= title.getRequires() && !hasTitle(playerId, title.getId())) {
						addTitle(playerId, title.getId());
					}
				}
			}
			break;
		case Constants.titleLevelUp:
			for (Title title : titles) {
				if (player.getLevel() >= title.getRequires() && !hasTitle(playerId, title.getId())) {
					addTitle(playerId, title.getId());
				}
			}
			break;
		case Constants.titlePrestige:
			/*int[] prestiges = ConstantsConfig.getPrestigeValues();
			Collection<Integer> curPrestiges = player.getDataInfo().getPrestiges();
			for (Title title : titles) {
				for (Integer curPre : curPrestiges) {
					if (curPre >= prestiges[title.getRequires()] && !hasTitle(playerId, title.getId())) {
						addTitle(playerId, title.getId());
					}
				}
			}*/
			break;
		case Constants.titleDiscipleRein:
			int[] disciples = new int[5];// 五种品质徒弟数量
			PlayerMartial playerMartial = Context.getDiscipleServer().getByPlayerId(playerId);
			for (Disciple d : playerMartial.getDisciples()) {
				disciples[d.getDiscipleMode().getQuality()]++;
			}
			for (Title title : titles) {
				if (disciples[title.getRequires()] >= title.getRequireNum() && !hasTitle(playerId, title.getId())) {
					addTitle(playerId, title.getId());
				}
			}
			break;
		case Constants.titleFriend:
			/*Collection<Friend> friends = player.getDataInfo().getFriends();
			for (Title title : titles) {
				if (friends.size() >= title.getRequires() && !hasTitle(playerId, title.getId())) {
					addTitle(playerId, title.getId());
				}
			}*/
			break;
		case Constants.titleSCpPass:
			final int passLevel = player.getDataInfo().intDataGet(ConstantsIntKey.soldierCpPass);
			Runnable r = new Runnable() {
				@Override
				public void run() {
					for (Title title : titles) {
						if (passLevel >= title.getRequires() && !hasTitle(playerId, title.getId())) {
							addTitle(playerId, title.getId());
						}
					}
				}
			};
			Context.getTimerServer().scheduleSeconds(r, delay);
			break;
		case Constants.titleQuiz:
			int integral = player.getDataInfo().intDataGet(ConstantsIntKey.quizScore);
			for (Title title : titles) {
				if (integral >= title.getRequires() && !hasTitle(playerId, title.getId())) {
					Context.getGeneralServer().addTitle(playerId, title.getId());
				}
			}
			break;
		case Constants.titlePet:
			//屏蔽宠物称号
			/*int petLevel = player.getPetLevel();
			for (Title title : titles) {
				if (petLevel / 10 + 1 >= title.getRequires() && !hasTitle(playerId, title.getId())) {
					Context.getGeneralServer().addTitle(playerId, title.getId());
				}
			}*/
			break;
		case Constants.titleWar://华山称号
			
			break;
		default:
			break;
		}
	}
	
	/**
	 * 检测一下是否激活某种修为奖励
	 * 
	 * @param playerId
	 */
	public void chkAwardActive(long playerId, int oldScore, int newScore) {
//		if (TimeProcesser.getUnixTime() >= ConstantsAct.mountainEndTime) {
//			return;
//		}
//		Player player = Context.getPlayerServer().getByPlayerId(playerId);
//		int comm = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.comm) ;
//		if ((comm & ConstantsDayIntKey.comm_4) == 0) {
//			player.getDataInfo().intDataAlter(ConstantsIntKey.tma, 1);
//			player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.comm, comm | ConstantsDayIntKey.comm_4);
//			player.getDataInfo().commitSync();
//		}
		
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		EventNotice eventNotice = new EventNotice(ConstantsRadio.comm, ConstantsRadio.commDailyItems);
		eventNotice.put("finishedItems", player.getDataInfo().getEveryDay().getDailyItem());
		eventNotice.put("dailyScore", newScore);			
		
		//神笔奖励
		int count = player.getDataInfo().intDataGet(ConstantsIntKey.pn);
		if (player.getLevel() >= ConstantsLevel.lv50Dragon && count < ConstantsModel.dragonPenGotMax) {
			for (int i = 0; i < ConstantsModel.dragonPenGot.length; i++) {
				if (newScore >= ConstantsModel.dragonPenGot[i][0] && oldScore < ConstantsModel.dragonPenGot[i][0]) {
					count = count + ConstantsModel.dragonPenGot[i][1] ;
					count =	count > ConstantsModel.dragonPenGotMax ? ConstantsModel.dragonPenGotMax : count;
					player.getDataInfo().intDataSet(ConstantsIntKey.pn, count);
					player.getDataInfo().commitSync();
					eventNotice.put("pnGot", ConstantsModel.dragonPenGot[i][1]);
					LogServer.recordLog(player, ConstantsLog.activity, 90504, newScore, ConstantsModel.dragonPenGot[i][1], count);
					break;
				}
			}
		}
		
		eventNotice.broadcast(playerId);
	}

}
